package com.maibow.controller.weixin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.maibow.controller.base.BaseController;
import com.maibow.entity.Page;
import com.maibow.entity.weixin.AccessToken;
import com.maibow.entity.weixin.WeixinTicket;
import com.maibow.interceptor.Token;
import com.maibow.service.organ.OrganService;
import com.maibow.service.system.CommonService;
import com.maibow.service.weixin.WeixinService;
import com.maibow.util.PageData;
import com.maibow.util.weixin.WeixinConstants;
import com.maibow.util.weixin.WeixinQRCodeUtil;
import com.maibow.util.weixin.WeixinUtil;

/**
 * 
 * 脉博网络后台管理系统
 * 包名：com.maibow.controller.party
 * 文件名：CommercialActivityPublishController.java
 * 作者: 吴比(Wubi)
 * 时间：2015年4月22日-下午8:27:42
 * Copyright@ 2015湖南脉博网络科技有限公司-版权所有
 *
 */
@Controller
@RequestMapping(value = "/weixinPomotion")
public class WeixinPomotionController extends BaseController {

    @Resource(name = "weixinService")
    private WeixinService weixinService;

    @Resource(name = "commonService")
    private CommonService commonService;

    @Resource(name = "organService")
    private OrganService organService;

    /**
     * 
     * queryWeixinPromotionlistPage(
     * 这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param session
     * 标记：@param page
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/list")
    public ModelAndView queryWeixinPromotionlistPage(HttpSession session, Page page) throws Exception {
        logBefore(logger, "推广人列表");
        ModelAndView modelView = new ModelAndView();
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();
            if (null != pageData.get("promotion_no") && !"".equals(pageData.get("promotion_no"))) {
                pageData.put("promotion_no", pageData.getString("promotion_no"));
            }

            if (null != pageData.get("promotion_name") && !"".equals(pageData.get("promotion_name"))) {
                pageData.put("promotion_name", pageData.getString("promotion_name"));
            }
            page.setPageData(pageData);
            List<PageData> varList = weixinService.queryWeixinPromotionlistPage(page);
            modelView.setViewName("system/weixin/weixin_pomotion_list");
            modelView.addObject("varList", varList);
            modelView.addObject("pageData", pageData);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return modelView;
    }

    @Token(save = true)
    @RequestMapping(value = "/goAddWeixinPomotion")
    public ModelAndView goAddWeixinPomotion(Page page) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();
        if (null != pageData.get("target_object")) {
            String target_object = pageData.get("target_object").toString();
            if (null != pageData.get("target_object_act")) {
                String message_type_act = pageData.get("target_object_act").toString();
                if ("2".equals(message_type_act)) {
                    pageData.put("target_object", 2);
                }
            } else {
                pageData.put("target_object", target_object); // 活动消息
            }
        }

        List<PageData> organList = organService.queryAllNormalOrganlistPage(page);
        modelView.setViewName("system/weixin/weixin_pomotion_add");
        modelView.addObject("varList", organList);
        modelView.addObject("pageData", pageData);
        return modelView;
    }

    /**
     * 
     * saveUser(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param out
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @Token(remove = true)
    @RequestMapping(value = "/saveWeixinPomotion")
    public ModelAndView saveWeixinPomotion(HttpServletRequest request, @RequestParam(value = "promotion_name", required = false) String promotion_name,
                        @RequestParam(value = "qrcode_type", required = false) String qrcode_type, @RequestParam(value = "target_object_current", required = false) String target_object_current,
                        @RequestParam(value = "org_id", required = false) String org_id) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = this.getPageData();
        // 推广人员名称
        pageData.put("promotion_name", promotion_name);
        pageData.put("qrcode_type", Integer.valueOf(qrcode_type));
        pageData.put("target_object", Integer.valueOf(target_object_current));
        if (target_object_current.equals("2")) {
            if (null != org_id && !"".equals(org_id)) {
                pageData.put("organ_id", Long.valueOf(org_id));
            }
        }
        WeixinQRCodeUtil util = new WeixinQRCodeUtil();
        WeixinUtil weixinUtil = new WeixinUtil();
        try {
            AccessToken accessToken = weixinUtil.getAccessTokenV3(WeixinConstants.CHUXIAN_PARTY_APPID, WeixinConstants.CHUXIAN_PARTY_SECRET);
            String token = accessToken.getAccessToken();
            JSONObject jsonParam = new JSONObject();
            Map<String, Object> map = new HashMap<String, Object>();
            if (qrcode_type.equals("1")) {
                // 临时二维码
                map.put("action_name", "QR_SCENE");
                map.put("expire_seconds", 2592000);
                pageData.put("qrcode_type", 1);
            } else {
                // 永久二维码
                map.put("action_name", "QR_LIMIT_STR_SCENE");
                pageData.put("qrcode_type", 2);
            }
            Map<String, Object> actionInfoMap = new HashMap<String, Object>();

            Map<String, Object> sceneMap = new HashMap<String, Object>();
            PageData promotionNoPageData = weixinService.findWeixinPromotionNo(pageData);
            long promotion_no = 1001;
            if (null != promotionNoPageData && promotionNoPageData.size() > 0) {
                promotion_no = Long.valueOf(promotionNoPageData.get("promotion_no").toString()) + 1;
            } else {
                promotion_no = 1;
            }

            // 推广人编号
            pageData.put("promotion_no", promotion_no);
            sceneMap.put("scene_id", promotion_no);

            // 这个参数只支持永久二维码
            if (qrcode_type.equals("2")) {
                sceneMap.put("scene_str", promotion_no);
            }
            actionInfoMap.put("scene", sceneMap);
            map.put("action_info", actionInfoMap);
            jsonParam.putAll(map);
            WeixinTicket ticket = util.getTicket(token, jsonParam);
            if (null != ticket.getTicket()) {
                String imageUrl = util.getQRCode(ticket.getTicket(), promotion_no);
                // 推广二维码
                pageData.put("qrcode_url", imageUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 创建机构
        weixinService.saveWeixinPromotion(pageData);
        modelView.addObject("msg", "success");
        modelView.setViewName("save_result");
        return modelView;
    }
}
